/**
 * 调试工具
 * 提供诊断页面卡死问题的实用函数
 */

import { MemoryManager, checkMemoryUsage } from './performanceOptimizations';
import { frontendVersionManager } from './version-manager';

export interface DiagnosticInfo {
  timestamp: string;
  userAgent: string;
  performance: {
    memory?: ReturnType<typeof checkMemoryUsage>['usage'];
    resourceStats: ReturnType<typeof MemoryManager.getStats>;
    timing: PerformanceTiming;
  };
  storage: {
    localStorage: { [key: string]: string };
    sessionStorage: { [key: string]: string };
  };
  version: {
    current: string;
    stored: string | null;
  };
  errors: string[];
}

/**
 * 收集完整的诊断信息
 */
export function collectDiagnosticInfo(): DiagnosticInfo {
  const errors: string[] = [];
  
  // 收集localStorage数据
  const localStorageData: { [key: string]: string } = {};
  try {
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      if (key) {
        localStorageData[key] = localStorage.getItem(key) || '';
      }
    }
  } catch (error) {
    errors.push(`localStorage访问失败: ${error}`);
  }

  // 收集sessionStorage数据
  const sessionStorageData: { [key: string]: string } = {};
  try {
    for (let i = 0; i < sessionStorage.length; i++) {
      const key = sessionStorage.key(i);
      if (key) {
        sessionStorageData[key] = sessionStorage.getItem(key) || '';
      }
    }
  } catch (error) {
    errors.push(`sessionStorage访问失败: ${error}`);
  }

  // 收集内存信息
  const memoryInfo = checkMemoryUsage();
  
  // 收集性能统计
  const resourceStats = MemoryManager.getStats();

  return {
    timestamp: new Date().toISOString(),
    userAgent: navigator.userAgent,
    performance: {
      memory: memoryInfo.usage,
      resourceStats,
      timing: performance.timing
    },
    storage: {
      localStorage: localStorageData,
      sessionStorage: sessionStorageData
    },
    version: {
      current: frontendVersionManager.getCurrentVersion(),
      stored: frontendVersionManager.getStoredVersion()
    },
    errors
  };
}

/**
 * 生成诊断报告
 */
export function generateDiagnosticReport(): string {
  const info = collectDiagnosticInfo();
  
  let report = `
=== 应用诊断报告 ===
生成时间: ${info.timestamp}
用户代理: ${info.userAgent}

=== 版本信息 ===
当前版本: ${info.version.current}
存储版本: ${info.version.stored || '未设置'}
版本一致: ${info.version.current === info.version.stored ? '是' : '否'}

=== 性能信息 ===
活跃定时器: ${info.performance.resourceStats.timers}
活跃间隔器: ${info.performance.resourceStats.intervals}
事件监听器: ${info.performance.resourceStats.listeners}
`;

  if (info.performance.memory) {
    const memory = info.performance.memory;
    report += `
内存使用: ${(memory.usedJSHeapSize / 1024 / 1024).toFixed(2)} MB
内存总量: ${(memory.totalJSHeapSize / 1024 / 1024).toFixed(2)} MB
内存限制: ${(memory.jsHeapSizeLimit / 1024 / 1024).toFixed(2)} MB
使用率: ${memory.usagePercent.toFixed(2)}%
`;
  }

  report += `
=== 页面性能 ===
DOM加载: ${info.performance.timing.domContentLoadedEventEnd - info.performance.timing.navigationStart}ms
页面加载: ${info.performance.timing.loadEventEnd - info.performance.timing.navigationStart}ms

=== 存储状态 ===
localStorage项目数: ${Object.keys(info.storage.localStorage).length}
sessionStorage项目数: ${Object.keys(info.storage.sessionStorage).length}

=== localStorage内容 ===
${Object.entries(info.storage.localStorage)
  .map(([key, value]) => `${key}: ${value.length > 100 ? value.substring(0, 100) + '...' : value}`)
  .join('\n')}

=== sessionStorage内容 ===
${Object.entries(info.storage.sessionStorage)
  .map(([key, value]) => `${key}: ${value.length > 100 ? value.substring(0, 100) + '...' : value}`)
  .join('\n')}
`;

  if (info.errors.length > 0) {
    report += `
=== 错误信息 ===
${info.errors.join('\n')}
`;
  }

  return report;
}

/**
 * 检查潜在的问题
 */
export function checkPotentialIssues(): Array<{
  type: 'warning' | 'error';
  message: string;
  suggestion: string;
}> {
  const issues: Array<{
    type: 'warning' | 'error';
    message: string;
    suggestion: string;
  }> = [];

  const info = collectDiagnosticInfo();

  // 检查版本一致性
  if (info.version.current !== info.version.stored) {
    issues.push({
      type: 'warning',
      message: '版本不一致，可能导致缓存问题',
      suggestion: '手动刷新页面或清除缓存'
    });
  }

  // 检查内存使用
  if (info.performance.memory && info.performance.memory.usagePercent > 80) {
    issues.push({
      type: 'error',
      message: `内存使用率过高: ${info.performance.memory.usagePercent.toFixed(2)}%`,
      suggestion: '关闭其他标签页或重启浏览器'
    });
  }

  // 检查资源泄露
  const stats = info.performance.resourceStats;
  if (stats.timers > 20) {
    issues.push({
      type: 'warning',
      message: `检测到大量定时器: ${stats.timers}`,
      suggestion: '可能存在内存泄露，建议刷新页面'
    });
  }

  if (stats.listeners > 50) {
    issues.push({
      type: 'warning',
      message: `检测到大量事件监听器: ${stats.listeners}`,
      suggestion: '可能存在内存泄露，建议刷新页面'
    });
  }

  // 检查存储使用
  const localStorageSize = JSON.stringify(info.storage.localStorage).length;
  if (localStorageSize > 5 * 1024 * 1024) { // 5MB
    issues.push({
      type: 'warning',
      message: `localStorage使用量过大: ${(localStorageSize / 1024 / 1024).toFixed(2)}MB`,
      suggestion: '清理不必要的缓存数据'
    });
  }

  // 检查页面加载时间
  const loadTime = info.performance.timing.loadEventEnd - info.performance.timing.navigationStart;
  if (loadTime > 10000) { // 10秒
    issues.push({
      type: 'warning',
      message: `页面加载时间过长: ${loadTime}ms`,
      suggestion: '检查网络连接或联系技术支持'
    });
  }

  // 检查错误
  if (info.errors.length > 0) {
    issues.push({
      type: 'error',
      message: `检测到${info.errors.length}个错误`,
      suggestion: '查看控制台获取详细错误信息'
    });
  }

  return issues;
}

/**
 * 紧急恢复功能
 */
export function emergencyRecovery(): void {
  console.warn('🚨 执行紧急恢复程序');
  
  try {
    // 1. 清理所有定时器和事件监听器
    MemoryManager.cleanup();
    
    // 2. 保存关键数据
    const userData = localStorage.getItem('userData');
    const appVersion = localStorage.getItem('app_cache_version');
    
    // 3. 清空所有存储
    localStorage.clear();
    sessionStorage.clear();
    
    // 4. 恢复关键数据
    if (userData) {
      localStorage.setItem('userData', userData);
    }
    if (appVersion) {
      localStorage.setItem('app_cache_version', appVersion);
    }
    
    // 5. 重新初始化应用状态
    sessionStorage.setItem('appInitialized', 'true');
    
    // console.log('✅ 紧急恢复完成');
    
    // 6. 显示恢复提示
    const notification = document.createElement('div');
    notification.innerHTML = `
      <div style="
        position: fixed;
        top: 20px;
        left: 50%;
        transform: translateX(-50%);
        background: #4CAF50;
        color: white;
        padding: 15px 25px;
        border-radius: 8px;
        font-size: 14px;
        z-index: 10000;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
      ">
        🚨 已执行紧急恢复，如问题持续请刷新页面
      </div>
    `;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
      if (document.body.contains(notification)) {
        document.body.removeChild(notification);
      }
    }, 5000);
    
  } catch (error) {
    // console.error('❌ 紧急恢复失败:', error);
    console.error('emergency recovery failed', error);
    
    // 最后的手段：强制刷新
    setTimeout(() => {
      window.location.reload();
    }, 1000);
  }
}

/**
 * 导出诊断数据
 */
export function exportDiagnosticData(): void {
  const report = generateDiagnosticReport();
  const blob = new Blob([report], { type: 'text/plain' });
  const url = URL.createObjectURL(blob);
  
  const a = document.createElement('a');
  a.href = url;
  a.download = `diagnostic-report-${Date.now()}.txt`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  
  URL.revokeObjectURL(url);
}

/**
 * 在开发环境中暴露调试工具到window对象
 */
if (import.meta.env.DEV) {
  (window as any).debugTools = {
    collectDiagnosticInfo,
    generateDiagnosticReport,
    checkPotentialIssues,
    emergencyRecovery,
    exportDiagnosticData,
    
    // 便捷方法
    diagnose: () => {
      // console.log('=== 诊断信息 ===');
      // console.log(generateDiagnosticReport());
      
      const issues = checkPotentialIssues();
      if (issues.length > 0) {
        console.warn('=== 发现问题 ===');
        issues.forEach(issue => {
          console.warn(`${issue.type.toUpperCase()}: ${issue.message}`);
          // console.log(`建议: ${issue.suggestion}`);
        });
      } else {
        // console.log('✅ 未发现明显问题');
      }
    },
    
    fix: emergencyRecovery
  };
  
  // console.log('🛠️ 调试工具已加载，使用 window.debugTools 访问');
  // console.log('  - debugTools.diagnose() - 诊断当前状态');
  // console.log('  - debugTools.fix() - 紧急修复');
  // console.log('  - debugTools.exportDiagnosticData() - 导出诊断报告');
} 

/**
 * 初始化调试工具
 * 在应用启动时调用，设置必要的监听器和诊断工具
 */
export function initDebugTools() {
  // 在开发环境中初始化调试工具
  if (process.env.NODE_ENV === 'development') {
    // console.log('🔧 初始化调试工具...');
    
    // 监听未捕获的异常
    window.addEventListener('error', (event) => {
      // console.error('🚨 未捕获的错误:', event.error);
      console.error('uncaught error', event.error);
    });
    
    // 监听未处理的Promise拒绝
    window.addEventListener('unhandledrejection', (event) => {
      // console.error('🚨 未处理的Promise拒绝:', event.reason);
      console.error('unhandled promise rejection', event.reason);
    });
    
    // 定期检查内存使用
    const memoryCheckInterval = setInterval(() => {
      const memoryInfo = checkMemoryUsage();
      if (memoryInfo.usage && memoryInfo.usage.usagePercent > 90) {
        // console.warn('⚠️ 内存使用率过高:', memoryInfo.usage.usagePercent.toFixed(2) + '%');
        console.warn('memory usage is too high', memoryInfo.usage.usagePercent.toFixed(2) + '%');
      }
    }, 30000); // 每30秒检查一次
    
    // 保存间隔器ID以便清理
    (window as any).__debugIntervals = {
      ...(window as any).__debugIntervals,
      memoryCheck: memoryCheckInterval
    };
    
    // console.log('✅ 调试工具初始化完成');
  }
} 